const mysql = require('mysql');
const config = require('./../config').database;

const pool = mysql.createPool({
    host: config.HOST,
    user: config.USERNAME,
    password: config.PASSWORD,
    database: config.DATABASE,
    timezone: "08:00"
});

let query = function(sql, values) {
    return new Promise((resolve, reject) => {
        pool.getConnection(function(err, connection) {
            if (err) {
                resolve(err);
            } else {
                connection.query(sql, values, (err, rows) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(rows);
                    }
                });
                connection.release();
            }
        })
    })
};

let insert = function(table, values) {
    let sql = 'INSERT INTO ?? SET ?';
    return query(sql, [table, values]);
};
let update = function(table, condition, info) {
    let sql = `UPDATE ?? SET ? WHERE ?`;
    return query(sql, [table, info, condition]);
};
// insert('book_info', { book_id: '21', tag: '22', price: '33' }).then((res) => {
//     console.log(res);
// }).catch((e) => {
//     console.log(e);
// });
// console.log(pool);
module.exports = {
    query,
    insert,
    update
}